<template>
  <div class="page">
    <gc-spread-sheets
      :hostClass="hostClass"
      @workbookInitialized="initWorkbook"
    />
  </div>
</template>

<script>
import "@grapecity/spread-sheets/styles/gc.spread.sheets.excel2016colorful.css";
import * as GC from "@grapecity/spread-sheets";
import "@grapecity/spread-sheets-vue";
import "@grapecity/spread-sheets-resources-zh";
GC.Spread.Common.CultureManager.culture("zh-cn");

export default {
  mounted() {},
  data() {
    return {
      hostClass: "spread-host",
      excelData: {
        data: [
          {
            "1月": {
              budgetYear: "2021",
              housingAverage: 5.3,
              averageNumberOfShops: 7.2,
              businessAverage: 6.1,
              officeAverage: 5.5,
              publicConstructionServicesAverage: 5.0,
              otherAverage: 5.0,
              unitPrice: 2.0,
              groundCarRentalUnitPrice: 1.8,
            },
          },
          {
            "2月": {
              budgetYear: "2021",
              housingAverage: 5.3,
              averageNumberOfShops: 7.2,
              businessAverage: 6.1,
              officeAverage: 5.5,
              publicConstructionServicesAverage: 5.0,
              otherAverage: 5.0,
              unitPrice: 2.0,
              groundCarRentalUnitPrice: 1.8,
            },
          },
        ],
      },
    };
  },
  methods: {
    initWorkbook: function (spread) {
      let activeSheet = spread.getActiveSheet();
      activeSheet.autoGenerateColumns = true;
        
      // 解析数据
      {
        let rows = [];
        let arr = Object.values(this.excelData.data);
        for (let index = 0; index < arr.length; index++) {
          let obj = arr[index];
          let data = Object.values(obj)[0];
          let datakeys = Object.keys(data);
          for (let i = 0; i < datakeys.length; i++) {
            const key = datakeys[i];
            const value = data[key];
            rows.push({ key, value });
          }
        }
        activeSheet.setDataSource(rows);
      }
      //解析列名
      {
        let cols = [{ size: 210, displayName: "key", name: "key" }];
        for (let index = 0; index < this.excelData.data.length; index++) {
          let obj = this.excelData.data[index];
          let key = Object.keys(obj)[0];
          cols.push({ displayName: key, name: "value" });
        }
        cols.push({ displayName: "" });
        console.log(JSON.stringify(cols));
        activeSheet.bindColumns(cols);
      }
    },
  },
};
</script>


<style scoped>
.spread-host {
  width: 100%;
  height: 600px;
}
</style>